package com.example.servletdemo.listner;

import sun.rmi.runtime.Log;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

/**
 * 网站在线人数统计
 */
//@WebListener
public class OnlineNumListner implements ServletContextListener, HttpSessionListener {
    private static final String TAG = "OnlineNumListner";

    private static String servletContextUserCountTag="userCount";
    private ServletContext servletContext;

    @Override
    public void contextInitialized(ServletContextEvent sce) {
        servletContext = sce.getServletContext();

        Integer userCount= (Integer) servletContext.getAttribute(servletContextUserCountTag);

        if(userCount==null) {
            userCount=0;
            servletContext.setAttribute(servletContextUserCountTag,userCount);
        }

        System.out.println(TAG+"=>contextInitialized:"+userCount);
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        Integer userCount= (Integer) servletContext.getAttribute(servletContextUserCountTag);
        userCount--;
        servletContext.setAttribute(servletContextUserCountTag,userCount);

        System.out.println(TAG+"=>contextDestroyed:"+userCount);
    }

    @Override
    public void sessionCreated(HttpSessionEvent se) {
        Integer userCount= (Integer) servletContext.getAttribute(servletContextUserCountTag);
        userCount++;
        servletContext.setAttribute(servletContextUserCountTag,userCount);

        System.out.println(TAG+"=>sessionCreated:"+userCount);
    }

    @Override
    public void sessionDestroyed(HttpSessionEvent se) {
        Integer userCount= (Integer) servletContext.getAttribute(servletContextUserCountTag);
        userCount--;
        servletContext.setAttribute(servletContextUserCountTag,userCount);

        System.out.println(TAG+"=>sessionDestroyed:"+userCount);
    }
}
